package com.carhailing.client.service.impl;
import com.carhailing.client.service.ClientService;
import com.carhailing.common.domain.response.StartCarOrder;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;


@Component
public class DelayedController{

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ClientService clientService;

    @RabbitListener(queues = "orderTradeQueue")
    public void orderTradeQueue(StartCarOrder startCarOrder, Message message, Channel channel){
        //使用uuid生成生产者id
        String uuid = UUID.randomUUID().toString();
        System.out.println("生产者id："+uuid);

        try {
            Long queue = redisTemplate.opsForSet().add("orderTradeQueue", uuid);

            if(queue==1){
                //如果状态没有改变就取消订单
                if(startCarOrder.getOrderStatus()==0){
                    System.out.println("订单取消");
                    clientService.delCarOrder(startCarOrder.getStartCarId());
                }
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //删除redis缓存里的key
            redisTemplate.delete("orderTradeQueue");

            try {
                //回退消息
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }


    }

}
